package com.buildings.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.buildings.BuildConfig;
import com.buildings.R;
import com.buildings.api.Api;
import com.buildings.api.Constant;
import com.buildings.base.BaseActivity;
import com.buildings.bean.LoginBean;
import com.buildings.bean.VersionBean;
import com.buildings.http.BaseCallBack;
import com.buildings.http.JsonBuilder;
import com.buildings.http.MyHttpClient;
import com.buildings.util.Base64Test;
import com.buildings.util.Base64Utils;
import com.buildings.util.CustomToast;
import com.buildings.util.DialogUtils;
import com.buildings.util.EncryptUtil;
import com.buildings.util.SPUtil;
import com.buildings.util.UpdateUtils;
import com.githang.statusbar.StatusBarCompat;
import com.tencent.bugly.crashreport.CrashReport;

import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.text.DecimalFormat;

import javax.crypto.Cipher;

import butterknife.ButterKnife;
import okhttp3.Call;


public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvForgetPassword;
    private EditText etPhone;
    private EditText etPassword;
    private Button btnLogin;
    private TextView btnRegister;
    private Dialog myDialog;
    Activity activity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.blue_5e), true);
        }
        activity = this;
        setContentView(R.layout.activity_login);
        initView();
        getVersion();

    }

    private void getVersion() {
        //  myDialog = DialogUtils.showRefreshDialog(activity);
//        JsonBuilder jsonBuilder = new JsonBuilder(this);
//        jsonBuilder.put("platform", "android");

        String url = Api.APP_VERSION + "?platform=" + "android";
        //网络请求获取版本信息
        MyHttpClient
                .newBuilder()
                .get()
                .url(url)
                //   .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<VersionBean>() {
                    @Override
                    public void onSuccess(VersionBean bean) {
                        super.onSuccess(bean);
                        if (null == bean.getData()) {
                            int isLogin = (int) SPUtil.get("isLogin", 0);
                            if (isLogin == 1) {
                                startActivity(new Intent(activity, MainTabActivity.class));
                                finish();
                            }
                        } else {
                            if (UpdateUtils.isUpdata(LoginActivity.this, bean.getData().getVersionAppCode())){
                                UpdateUtils.showUpdateConfirmDialog(LoginActivity.this, bean.getData(), true);
                            }else {
                                int isLogin = (int) SPUtil.get("isLogin", 0);
                                if (isLogin == 1) {
                                    startActivity(new Intent(activity, MainTabActivity.class));
                                    finish();
                                }
                            }
                        }

//                        if (updataBean.getUpdate() == 1) {
//                            showUpdateConfirmDialog(context, updataBean, isForceCheck);
//                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        int isLogin = (int) SPUtil.get("isLogin", 0);
                        if (isLogin == 1) {
                            startActivity(new Intent(activity, MainTabActivity.class));
                            finish();
                        }
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        int isLogin = (int) SPUtil.get("isLogin", 0);
                        if (isLogin == 1) {
                            startActivity(new Intent(activity, MainTabActivity.class));
                            finish();
                        }
                    }
                });
    }

    private void initView() {
        tvForgetPassword = findViewById(R.id.tv_forget_password);
//        tvForgetPassword.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
//        tvForgetPassword.getPaint().setAntiAlias(true);//抗锯齿
        tvForgetPassword.setOnClickListener(this);
        etPhone = findViewById(R.id.et_phone);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this);
        btnRegister = findViewById(R.id.tv_register);
        btnRegister.setOnClickListener(this);

//        etPhone.setText("18434163012");

//        etPhone.setText("13439178769");
//        etPhone.setText("15011140668");
//        etPassword.setText("111111");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_forget_password:
                startActivity(new Intent(activity, ResetPasswordActivity.class));
                break;
            case R.id.btn_login:
//                startActivity(new Intent(activity,MainTabActivity.class));
                if (TextUtils.isEmpty(etPhone.getText().toString())) {
                    CustomToast.showToast(activity, "请输入手机号");
                    return;
                }
                if (etPhone.getText().toString().length() != 11) {
                    CustomToast.showToast(activity, "请输入正确手机号");
                    return;
                }
                if (TextUtils.isEmpty(etPassword.getText().toString())) {
                    CustomToast.showToast(activity, "请输入密码");
                    return;
                }
                myDialog = DialogUtils.showRefreshDialog(activity);

                login(etPhone.getText().toString(), etPassword.getText().toString());
                break;
            case R.id.tv_register:
//                CrashReport.testJavaCrash();
                startActivity(new Intent(activity, RegisterActivity.class));
//                String data = "5A001ACC000000000000000000008C5B0005AE010700F6";
//                test(data);
                break;
        }
    }

    public void test(String data) {
        if (data.length() >= 46 && data.length() <= 48) {
            if (data.substring(0, 2).equals("5B")) {
                String tizhong00 = data.substring(21, 25);
                int dec_num00 = (int) Long.parseLong(tizhong00, 16);
                String result = division(dec_num00, 100);
                Log.e("", result);
            } else {
                String tizhong0 = data.substring(4, 8);  //50   54
                int dec_num0 = (int) Long.parseLong(tizhong0, 16);
                String result = division(dec_num0, 100);
                Log.e("", result);
            }
        }
    }

    public static String division(int a, int b) {
        String result = "";
        float num = (float) a / b;
        DecimalFormat df = new DecimalFormat("0.0");
        result = df.format(num);
        return result;
    }

    private void login(final String phone, String password) {

        String encryptStr = EncryptUtil.encryptString(password, Constant.PUBLIC_KEY);

        JsonBuilder jsonBuilder = new JsonBuilder(this);
//        jsonBuilder.put("userName", phone);
        jsonBuilder.put("cipher", encryptStr);
        jsonBuilder.put("appCode", Constant.APP_CODE);

        final String finalEncryptStr = encryptStr;
        MyHttpClient
                .newBuilder()
                .post()
//                .url(Api.LOGIN+"/"+"fwadmin"+"/login")
                .url(Api.LOGIN + "/" + phone + "/login")
                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<LoginBean>() {
                    @Override
                    public void onSuccess(LoginBean bean) {
                        super.onSuccess(bean);
//{"code":200,"data":{"success":true,"errorCode":null,"errorMessage":null,"retryTimes":0,"remainLockedTime":null,"userId":"ca3ca0d0d557424d94ec8009b6ca6d08","token":"eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiJhNGQ1MTkxZC01ZjY0LTQ5YjEtYTk4NS01NjM2YTA5ZDc1M2EiLCJpYXQiOjE1ODk1MzMxNDksInN1YiI6IjkzNWQ4MzNkZGU0MjRlMWJhYzdmZWVjM2M0MDZhMDI5IiwiZXhwIjoxNTg5NTMzNTQ5fQ.KGhav1E8SLuHXkb60RsbWj3xLMscIPrGmvDSmPjSLr4"},"message":null}
                        if (bean.getCode() == 200) {
                            if (bean.getData().isSuccess()) {
                                SPUtil.save("token", bean.getData().getToken());
                                SPUtil.save("userId", bean.getData().getUserId());
                                SPUtil.save("isLogin", 1);
                                SPUtil.save("phone", phone);
                                SPUtil.save("password", finalEncryptStr);
                                startActivity(new Intent(activity, MainTabActivity.class));
                                finish();
                            } else {
                                if (TextUtils.equals("TOO_MANY_FAILURES", bean.getData().getErrorCode())) {
                                    CustomToast.showToast(activity, "账户已被锁定");
                                } else {
                                    CustomToast.showToast(activity, "用户名或密码错误");
                                }
                            }
                        } else {
                            CustomToast.showToast(activity, "用户名或密码错误");
                        }
                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(LoginActivity.this, "网络异常");
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(LoginActivity.this, "网络异常");
                    }
                });

    }


//        RequestBody requestBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                .addFormDataPart("contentFile", fileUrl)
//                .addFormDataPart("relationId", relationId + "")
//                .addFormDataPart("fromUserId", doctorId + "")
//                .addFormDataPart("fromUserName", doctorName + "")
//                .addFormDataPart("toUserId", patientId + "")
//                .addFormDataPart("msgType", msgType)
//                .addFormDataPart("msgContent", msgContent)
//                .addFormDataPart("pgType", 1 + "")
//                .addFormDataPart("imgWidth", width + "")
//                .addFormDataPart("imgHeight", height + "")
//                .addFormDataPart("duration", times)
//                .build();
//        long time = new Date().getTime();
//        ConsultationDetailBean detailBean = new ConsultationDetailBean();
//        detailBean.setDoctorId(doctorId+"");
//        detailBean.setCreateTime(time);
//        detailBean.setMsgId(time+"");
//        detailBean.setVoice(false);
//        detailBean.setFromUserId(doctorId+"");
////        detailBean.setDuration(TextUtils.isEmpty(times)?0:Integer.parseInt(times));
//        detailBean.setFromUserHeadImage(userHeadImage);
//        detailBean.setImgHeight(width);
//        detailBean.setImgHeight(height);
//
//        final Request request = new Request.Builder()
//                .url(Api.UPMSG_URL)
//                .post(requestBody)
//                .build();
//        OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
//
//        OkHttpClient okHttpClient = httpBuilder.build();

//        okHttpClient.newCall(request).
//
//                enqueue(new Callback() {
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        if(dialog != null){
//                            dialog.dismiss();
//                        }
//                        activity.runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                CustomToast.showToast(ConsultionDetailActivity.this, "网络异常，发送失败");
//                            }
//                        });
//                    }
//
//
//                    @Override
//                    public void onResponse(Call call, Response response) throws IOException {
//                        if(dialog != null){
//                            dialog.dismiss();
//                        }
//                        String htmlStr = response.body().string();
//
//                        Log.e("返回数据:", htmlStr);
//                        JSONObject json = JSON.parseObject(htmlStr.toString());
//                        if (json.getString("retCode").equals("0000")) {
//                            // Toast.makeText(MyMedicalRecordActivity.this, "提交病历成功", Toast.LENGTH_SHORT).show();
//                            //etContent.setText("");
//
//                            http(true);
//                            destoryBimap();
//                            if (type == 1) {
//                                MediaRecorderDelete(fileUrl);
//                            }
//                        } else if (json.getString("retCode").equals("0009")) {
//                            new Thread() {
//                                public void run() {
//                                    handler.post(runnableUi1);
//                                }
//                            }.start();
//                        }else if(TextUtils.equals("0003",json.getString("retCode"))){
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    CustomToast.showToast(ConsultionDetailActivity.this, "本次咨询已经超过24小时，系统已经自动结束");
//                                }
//                            });
//                        }
//
//                    }
//
//                });

    private static String RSA = "RSA/ECB/PKCS1Padding";
    private static String RSA_KEY_FACTORY = "RSA";

    /**
     * 用公钥加密 <br>
     * 每次加密的字节数，不能超过密钥的长度值减去11
     *
     * @param data      需加密数据的byte数据
     * @param publicKey 公钥
     * @return 加密后的String型数据
     */
    public static String encryptDataStr(byte[] data, PublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA);
            // 编码前设定编码方式及密钥
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            // 传入编码数据并返回编码结果
            return Base64Utils.encode(cipher.doFinal(data));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
            InvalidKeySpecException {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_FACTORY);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }


}
